//
//  FmdbDataManager.swift
//  YourName
//
//  Created by effort on 2017/5/22.
//  Copyright © 2017年 李朋. All rights reserved.
//

import Foundation
import FMDB

class FmdbDataManager {
    static let shared = FmdbDataManager()
    
    
    fileprivate let queue:FMDatabaseQueue
    
    init() {
        
        ///初始化数据库
        
        let tabelName = "Diary.db"
        
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        path = (path as NSString).appendingPathComponent(tabelName)
        
        queue = FMDatabaseQueue(path: path)
        
        print("\(path)")
        ///创建数据库
        createTableData()
    }
}

extension FmdbDataManager {
    
    
    /// 存储一组日记
    ///
    /// - Parameter diarys: 日记数组
    func updataDiarys(diarys:[String]) {
        
        queue.inTransaction { (db, callBack) in
            for diary in diarys {
                let sql = "INSERT OR REPLACE into T_Diary (diary) VALUES (?);"
                if db?.executeUpdate(sql, withArgumentsIn: [diary]) == false {
                    callBack?.pointee = true
                    break
                }
            }
        }
    }
    
    
    /// 存储单个日记
    ///
    /// - Parameter diarys: 单个
    func updataDiary(diary:String) {
        
        queue.inDatabase { (db) in
            let sql = "INSERT or REPLACE into T_Diary (diary) VALUES (?);"
            if db?.executeUpdate(sql, withArgumentsIn: [diary]) == true {
                print("存储成功")
            }
        }
        
    }
    
    
    /// 查询数据库
    ///
    /// - Returns: 日记列表
    func getArray(diaryId:Int) -> [[String:AnyObject]] {
        
        let sql = "select * FROM T_Diary where diaryId < ? ORDER BY diaryId DESC LIMIT 10;"
        
        var diarys = [[String:AnyObject]]()
        queue.inDatabase { (db) in
            guard let set = db?.executeQuery(sql, withArgumentsIn: [diaryId]) else {
                return
            }
            while set.next() {
                var diary = [String:AnyObject]()
                diary["diaryId"] = set.object(forColumnName: "diaryId") as! Int as AnyObject
                diary["diary"] = set.object(forColumnName: "diary") as! String as AnyObject
                diarys.append(diary)
            }
        }
        return diarys
    }
}

fileprivate extension FmdbDataManager {
    
    /// 创建或者打开数据库
    func createTableData() {
  
        guard let path = Bundle.main.path(forResource: "diary.sql", ofType: nil),
              let sql = try? String(contentsOfFile: path) else {
            return
        }
        
        queue.inDatabase { (db) in
            if db?.executeStatements(sql) == true {
                print("创表成功")
            }else {
                print("创表失败")
            }
        }
    }
}













